package mq

import (
	"encoding/json"
	"fmt"

	"github.com/streadway/amqp"
	"github.com/we-pay-kit/we-pay-kit/internal/logger"
)

// Producer provides high-level JSON publishing helpers.
type Producer struct {
	client *RabbitMQClient
}

func NewProducer() *Producer {
	return &Producer{client: GetRabbitMQ()}
}

// EnsureQueue declares a durable queue idempotently.
func (p *Producer) EnsureQueue(name string) error {
	if p.client == nil || p.client.channel == nil {
		return fmt.Errorf("rabbitmq not initialized")
	}
	_, err := p.client.channel.QueueDeclare(
		name,
		true,                               // durable
		false,                              // auto-delete
		false,                              // exclusive
		false,                              // no-wait
		amqp.Table{"x-queue-mode": "lazy"}, // reduce memory peaks
	)
	return err
}

// PublishJSON marshals the payload to JSON and publishes to the queue.
func (p *Producer) PublishJSON(queue string, payload interface{}) error {
	if p.client == nil || p.client.channel == nil {
		return fmt.Errorf("rabbitmq not initialized")
	}

	if err := p.EnsureQueue(queue); err != nil {
		return err
	}

	body, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	pub := amqp.Publishing{
		ContentType:  "application/json",
		Body:         body,
		DeliveryMode: amqp.Persistent,
	}

	if err := p.client.channel.Publish("", queue, false, false, pub); err != nil {
		logger.Error(fmt.Sprintf("publish failed: %v", err))
		return err
	}
	return nil
}
